/** @类 解析类 */
export class Parser {
  constructor() {
    this.scale = {
      rate: 1, // 计算最小缩放率（背景不超出画布）
      scaling: 1, // 当前缩放比例
      step: 0.2, // 缩放步长
      min: 1, // 最小缩放比例
      max: 30, // 最大缩放比例
    };
    this.wrapper = {
      lineWidth: 2,
      lineColor: 'rgba(255,255,255,0.5)',
      backgroundColor: 'rgba(0,0,0,0.5)',
    };
    this.background = {
      src: '', // 背景图片
      width: 0, // 背景宽度
      height: 0, // 背景高度
      offsetX: 0, // 偏移坐标X
      offsetY: 0, // 偏移坐标Y
    };
    this.stages = [];
    this.activeIndex = -1;
  }

  /** @方法 加载项目 */
  load({ data, observer, renderer }) {
    // 判断背景尺寸变更, 重新计算比例
    if (
      this.background.width != data.background.width ||
      this.background.height != data.background.height
    ) {
      this.scale.scaling = 1;
      this.scale.rate = renderer.width / data.background.width;
      this.background.width = data.background.width;
      this.background.height = data.background.height;
      this.background.offsetX = 0;
      this.background.offsetY = 0;
    }
    // 判断背景图片变更, 滚动恢复初始
    if (this.background.src != data.background.src) {
      this.background.src = data.background.src;
      this.background.image = null;
      this.GetBackground(this.background);
    }
    this.stages = data.stages;
    this.wrapper = {
      ...data.wrapper,
    };
    this.activeIndex = -1;
    observer.dispatch('loaded', this);
  }

  /** @方法 选中地块 */
  selected(index) {
    this.activeIndex = index;
  }

  /** @方法 获取点击地块 */
  clickStage(point) {
    const { x, y } = point;
    const index = this.stages.findIndex(({ polygon }) => {
      let inside = false;
      for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
        const xi = polygon[i].x;
        const yi = polygon[i].y;
        const xj = polygon[j].x;
        const yj = polygon[j].y;

        if (((yi > y) !== (yj > y)) && (x < ((xj - xi) * (y - yi)) / (yj - yi) + xi)) {
          inside = !inside;
        }
      }
      return inside;
    });
    this.activeIndex = index === this.activeIndex ? -1 : index;
    return { index: this.activeIndex };
  }

  /** @辅助 加载背景 */
  GetBackground(background) {
    if (this.background.src) {
      const image = new Image();
      image.src = background.src;
      image.addEventListener('load', () => (background.image = image));
    }
  }
}

export default Parser;
